<?php
include_once(APP_PATH.'/sms/configs/sms_config.php');
class sms_model_system extends sms_model_data {
	var $msgType = array(
		sms_config::MSG_ALL => 0, //所有消息
		sms_config::MSG_SYS_FRIENDS => '[:friends|add:]', //好友请求
		sms_config::MSG_SYS_GIFT => '[:gift:]', //礼物类型
		sms_config::MSG_SYS_BUFF => '[:buff:]', // 技能类型
		sms_config::MSG_SYS_CITE => '[:cite:]' //转帖类型
	);
	public function __construct(){
		parent::__construct();
		$this->table = 'app_sms_notice';
		$this->reltable = 'app_sms_notice_reciever';
	}
	/**
	 * 发送短消息接口：
	 *
	 * @param array $args
	 * @return int ;
	 */
	public function add($args){ 
//		$args = filter_params($args, 'senderid', 'sender','recieverid', 'reciever', 'content', 'target');
		trim_params($args);
		$args['dateline'] = time();
		if($id = $this->db->insert($this->table, $args)){			
			$target = unserialize($args['target']);
			$target['id'] = $id;
			$sql = 'UPDATE '.$this->table.' SET target =&target  WHERE sms_id=&id';
			$para = array(
						'id' =>$id,
						'target' => serialize($target)
					);
			$this->db->query($sql,$para);
			/**
			 * 添加分表记录
			 */
			$args['sms_id'] = $id;
			$args['target'] = $para['target'];
			$this->addSubTable($args);
			//分表添加结束
			$this->updateNoticeNums($args,1);
			return $id;
		}
		return false;
	}
	
	/**
	 * 添加分表记录
	 * Enter description here ...
	 * @param unknown_type $args
	 */
	public function addSubTable($args){
		$tbname = sms_util_system::getTableName($args['recieverid']);
		return $this->db->insert($tbname, $args);
	}
	
	/**
	 * 发送短消息-添加会话关系接口
	 *
	 * @param unknown_type $args
	 * @return unknown
	 */
	public function addRel($args){
		$sender = $args['sender'];
		$args = filter_params($args, 'sms_id', 'reciever_id','reciever', 'readed');
		trim_params($args);
		if($msid = $this->db->insert($this->reltable, $args)){
			$args['sender'] = $sender;
			$this->updateNoticeNums($args,1);
		}
		return $msid?$msid:false;
	}
	
	/**
	 * 更新未读系统消息数
	 *
	 * @param unknown_type $param
	 * @param unknown_type $type
	 */
	private   function updateNoticeNums(&$param,$type=1){
		if($param['senderid']==0 ){
			$sender = $param['sender'];
			if($sender && $sender = $this->parseSenderNames($sender)){
				$msgType = array_flip($this->msgType);
			}
			$type = $msgType[$sender]?$msgType[$sender]:sms_config::MSG_SYS_SMS_CNT;
		}
		$type = $type?$type:sms_config::MSG_SYS_SMS_CNT;
		$data = $this->factory('sms_model_data');
		if(is_array($param['recieverid']) && !empty($param['recieverid'])){
			foreach ($param['recieverid'] as $v){
				$data->updateSmsCount($v,$type,1);
			}
		}else{
			$data->updateSmsCount($param['recieverid'],$type,1);
		}
		unset($data);
		return ;
	}
	
	/**
	 * 删除系统消息
	 *
	 * @param unknown_type $uid
	 * @param unknown_type $id
	 * @return unknown
	 */
	public function deleteSystem($uid,$id='',$type = 0){
		if(!$uid) return false;
//		$sql = 'DELETE FROM '.$this->table.'  WHERE recieverid='.$uid;
		$where = '  WHERE recieverid='.$uid;
		if($id){
			if(is_array($id) && !empty($id)){
				$id = implode(',',$id);
			}
			$where .= '  AND sms_id IN ('.$id.')';
		}
		if($type>0 && $this->msgType[$type]){
			$where .= ' AND sender = \''.$this->msgType[$type].'\' ';
		}
//		$params = array('uid'=>$uid);
		$sql = 'DELETE FROM '.$this->table.$where;
		if($this->db->query($sql)){
			$this->db->query('DELETE FROM '.sms_util_system::getTableName($uid).$where);
			return true;
		}
		return false;
	}
	
	/**
	 * 删除系统消息
	 *
	 * @param unknown_type $uid
	 * @param unknown_type $id
	 * @return unknown
	 */
	public function removeSystem($id,$uid,$type = 0){
		if(!$id) return false;
		is_array($id) && $id = implode(',', $id);
//		$sql = 'UPDATE '.$this->table.' SET isdelete = 1  WHERE recieverid=&uid ';
		$where  = ' DELETE FROM '.$this->table.' WHERE sms_id IN ('.$id.') ';
		if(is_numeric($uid) && $uid>0) $where.=' AND recieverid='.$uid;
		if($type>0 && $this->msgType[$type]){
			$where .= ' AND sender = \''.$this->msgType[$type].'\' ';
		}
		if($this->db->query(' DELETE FROM '.$this->table.$$where)){
			//删除分表记录
			$this->db->query(' DELETE FROM '.sms_util_system::getTableName($uid).$where);
		}
	}
	
	/**
	 * 获取系统收件箱列表
	 *
	 * @param unknown_type $uid
	 * @param unknown_type $page
	 * @param unknown_type $pageSize
	 * @param unknown_type $type
	 * @return unknown
	 */
	public function selectSysInboxPage($uid, $page, $pageSize,$type = ''){
		$msgtype = '';
		if($type!=='' && array_key_exists($type,$this->msgType)){
			$msgtype = $this->parseSenderNames($this->msgType[$type]);
		}
		$tbname = sms_util_system::getTableName($uid);
		$sql = 'SELECT a.sms_id,a.senderid AS sender_id,a.sender AS sender_name,a.recieverid,a.reciever,a.title,a.content,a.dateline AS create_time,a.target,a.readed AS unread FROM '.$tbname.' a   WHERE  a.recieverid='.$uid.' AND a.isdelete=0 '.($msgtype?'AND a.sender = \''.$msgtype.' \'':'').'ORDER BY a.sms_id DESC ';
		$params = array('uid'=>$uid);
		return $this->db->selectPage($sql, $params, $page, $pageSize );
	}
	private function parseSenderNames($str){
		$regex = "`\[\:([a-z0-9]+)(?:\|[a-z0-9]+)?\:\]`";
		$flag = preg_match($regex, $str, $match);
		if($flag){
			return $match[0];
		}else{
			return NULL;
		}
	}
	
	/**
	 * 列出所有系统消息列表(后台使用)
	 * Enter description here ...
	 * @param unknown_type $uid 用户id 为空表示所有系统消息
	 * @param unknown_type $page 页数  
	 * @param unknown_type $pageSize 页大小
	 * @param unknown_type $type 系统消息类型
	 */
	public function getSysInboxPage($uid='',$page=1,$pageSize=25,$type='',$start_time='',$endtime=''){
		$msgtype = $where = '';
		if($type!=='' && array_key_exists($type,$this->msgType)){
			$msgtype = $this->parseSenderNames($this->msgType[$type]);
		}
		$sql = 'SELECT a.sms_id,a.senderid AS sender_id,a.sender AS sender_name,a.recieverid,a.reciever,a.content,a.dateline AS create_time,a.target,a.readed AS unread FROM '.$this->table.' a   ';
		if($uid && is_numeric($uid)){
			$where.=' a.recieverid='.$uid;
		}
		if($msgtype){
			$where.= ($where?' AND ':' ').'a.sender=\''.$msgtype.'\'';
		}
		if($start_time){
			$st = date_parse($start_time);
			$starttime =gmmktime($st['hour'], $$st['minute'], $st['second'], $st['month'], $st['day'], $st['year']);
			if($end_time){
				$st = date_parse($end_time);
				$endtime =gmmktime($st['hour'], $$st['minute'], $st['second'], $st['month'], $st['day'], $st['year']);
			}else
				$endtime = time();
			$where.= ($where?' AND ':' ').' dateline>='.$starttime.' AND dateline<='.$endtime;
		}
		$sql.=($where?' WHERE'.$where:'').' ORDER BY a.sms_id DESC ';
		return $this->db->selectPage($sql, $params, $page, $pageSize );
	}
	
	/**
	 * 获取单条短消息信息
	 *
	 * @param unknown_type $sms_id
	 * @return unknown
	 */
	public function select($sms_id){
		$sql = "SELECT a.sms_id, a.senderid, a.sender AS username, a.title, a.recieverid, a.dateline, a.isdelete, a.target  FROM ".$this->table." a WHERE a.sms_id=&id";
		$params = array('id'=>$sms_id);
		return $this->db->fetchRow($sql, $params);
	}
	/**
	 * 获取各种未读消息数
	 *
	 * @param unknown_type $uid
	 * @return unknown
	 */
	public function queryUnReadSms($uid){
		if(!is_numeric($uid)) return false;
		$sql = "SELECT asc_sms as smsnum,asc_sysann as sysnum,asc_comment as comnum,asc_message as msgnum,asc_friends as friendsnum,asc_buff as buffnum,asc_gift as giftnum FROM app_sms_count WHERE uid=&uid ";
		$params = array('uid' =>$uid);
		return $this->db->fetchRow($sql, $params);
	}
	/**
	 * 更新消息状态
	 *
	 * @param unknown_type $id
	 * @param unknown_type $target
	 * @return unknown
	 */
	public function updateTarget($id, $target){
		$sql = 'UPDATE '.$this->table." SET target=&target WHERE sms_id=&id" ;
		$target['id'] = $id;
		$params = array(
			'id'=>$id,
			'target'=>serialize($target)
		);
		if($this->db->query($sql, $params)){
			$notice = $this->select($id);
			$tbname = sms_util_system::getTableName($notice['recieverid']);
			$sql = 'UPDATE '.$tbname." SET target=&target WHERE sms_id=&id" ;
			$this->db->query($sql, $params);
			return true;
		}
		return false;
	}
	
	
	public function getSysNoticeByUid($senderid,$reciverid, $type){
		$tbname = sms_util_system::getTableName($reciverid);
		$sql = " SELECT * FROM ".$tbname.' where senderid='.$senderid.' AND recieverid='.$reciverid.' && sender=\''.$type.'\'';
		return  $this->db->fetchRow($sql);
	}
	
	
	/**
	 * 回滚事务
	 *
	 * @param unknown_type $sms_id
	 * @param unknown_type $type
	 * @return unknown
	 */
	public function rollback($sms_id,$type=true){
		$sql = "DELETE from ".$this->table." where sms_id=&sms_id";
		$params = array('sms_id'=>$sms_id);
		return $this->db->query($sql, $params);
	}
	
	public function getDuelUsers(){
		$sql = 'SELECT uid,username FROM app_duel_player WHERE level>=10';
		return $this->db->fetchAll($sql);
	}
	
	public function setActiveCodeLog($uid,$key,$flag=1){
		$sql = " INSERT INTO active_code_log VALUES(NULL,{$uid},'{$key}',$flag);";
		return $this->db->query($sql);
	}
	
	public function isCiteNotice($uid){
//		$this->db->query(' DELETE FROM app_sms_citenotice WHERE uptime<'.time()-CACHE_EXPIRY_TIME);
		$sql = 'SELECT * FROM app_sms_citenotice WHERE uid='.$uid;
		if($rst = $this->db->fetchRow($sql)){
			if($rst['flag']==0) return false;
			if(time()-$rst['uptime']>CACHE_EXPIRY_TIME) {//如果过期
				$this->db->query('UPDATE app_sms_citenotice SET uptime='.time().' WHERE uid='.$uid);
				return true;
			}
			return false;
		}
		return $this->db->query('INSERT INTO app_sms_citenotice VALUES('.$uid.','.time().',1)');
	}
	
	public function refuseCiteNotice($uid){
		if(!is_numeric($uid)) return false;
		return $this->db->query('UPDATE app_sms_citenotice SET flag=0,uptime='.time().' WHERE uid='.$uid);
	}
}